package com.siashan.toolkit.core.page;

import lombok.Getter;
import lombok.Setter;

import java.util.Collections;
import java.util.List;

/**
 * 分页Page类
 *
 * @author siashan
 * @since v1.0.7
 */
@Setter
@Getter
public class PageInfo<T> {
	/**
     * 页码，从1开始
     */
    private int pageNum = 0;
    /**
     * 页面大小
     */
    private int pageSize = 10;
    /**
     * 起始行
     */
    private int startRow;
    /**
     * 结束行
     */
    private int endRow;
    /**
     * 总数
     */
    private int total;
    /**
     * 总页数
     */
    private int pages;
    /**
     * 上一页
     */
    private int prePage;
    /**
     * 下一页
     */
    private int nextPage;

    /**
     * 是否第一页
     */
    private boolean isFirstPage;
    /**
     * 是否最后一页
     */
    private boolean isLastPage;
    /**
     * 是否有上一页
     */
    private boolean hasPreviousPage;
    /**
     * 是否有下一页
     */
    private boolean hasNextPage;

    /**
     * 查询数据列表
     */
    private List<T> records = Collections.emptyList();



    public PageInfo(int pageNum, int pageSize, int total,List<T> records){
    	this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.total = total;
        this.records = records;
        // 计算起止行号
        calculateStartAndEndRow();
        // 计算总页码
        calcPages();
        // 计算分页边界
        judgePageBoudary();
    }


    /**
     * 计算起止行号
     */
    private void calculateStartAndEndRow() {
        this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0;
        this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0);
    }

    /**
     * 计算分页边界
     */
    private void judgePageBoudary() {
        this.isFirstPage = this.pageNum == 1;
        this.isLastPage = this.pageNum == this.pages || this.pages == 0;
        this.hasPreviousPage = this.pageNum > 1;
        this.hasNextPage = this.pageNum < this.pages;
    }

    /**
     * 设置总条目
     *
     * @param total 总条目
     */
	public void setTotal(int total) {
		this.total = total;
        if (pageSize > 0) {
            pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1));
        } else {
            pages = 0;
        }
	}

    /**
     * 计算页码
     *
     */
    private void calcPages() {
        if (this.pageSize > 0) {
            this.pages = (int) (this.total / this.pageSize + ((this.total % this.pageSize == 0) ? 0 : 1));
        } else {
            this.pages = 0;
        }
        if (this.pageNum > 1) {
            this.prePage = this.pageNum - 1;
        }

        if (this.pageNum < this.pages) {
            this.nextPage = this.pageNum + 1;
        }
    }

}
